﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using ATW.MT.BUS;
using System.Text;
using ATW.MT.CommonClass;
using System.Collections;
using BUS;
using DAL.Dao;

namespace ATW.MT.SellManage
{
    public partial class OverRelaxation : System.Web.UI.Page
    {
        bus_T_Request request = new bus_T_Request();
        CommonHelp CH = new CommonHelp();
        MessageDao _MessageDao = new MessageDao();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewState["finished"] = new ArrayList();//完成修改的记录
                BindData();
            }
        }
        private void BindData()
        {//根据id查找报价
            string reqid = Request.QueryString["requestid"];
            if (!string.IsNullOrEmpty(reqid) && CommonClass.common.filterChar(reqid))
            {
                hdfReqID.Value = reqid;
                try
                {
                    DataTable dtHead = new DataTable();
                    DataTable dtList = new DataTable();
                    GetData(reqid, ref dtHead, ref dtList);
                    //if (dtList != null && dtList.Rows.Count > 0)
                    //{
                    //    for (int i = 0; i < dtList.Rows.Count; i++)
                    //    {
                    //        string reqDetailID = dtList.Rows[i]["ReqDetailID"].ToString();
                    //        string resDetailID = dtList.Rows[i]["ResDetailID"].ToString();
                    //        if (resDetailID == "")
                    //        {
                    //            string _status = "";
                    //            resDetailID = request.getResDetail(reqDetailID, out _status);
                    //            if (_status == "1")//无需处理
                    //            {
                    //                dtList.Rows[i]["rowstatus"] = "ex";
                    //            }
                    //        }
                    //    }
                    //}
                    //DataView dv1 = dtList.DefaultView;
                    //dv1.RowFilter = "rowstatus<>'ex'";
                    //dtList = dv1.ToTable();
                    ViewState["dtList"] = dtList;
                    //DataView dv = dtHead.DefaultView;
                    //dv.RowFilter = "rowstatus='9'";//筛出要处理的项
                    //dtHead = dv.ToTable();
                    rpList.DataSource = dtHead;
                    rpList.DataBind();
                    //判断是否完成本单操作
                    DataView dv = dtList.DefaultView;
                    dv.RowFilter = "rowstatus='9'";
                    DataTable _list = dv.ToTable();
                    ArrayList finished = (ArrayList)ViewState["finished"];
                    if (_list.Rows.Count == finished.Count)
                    {//本单操作已经完成
                        //提示
                        Tips("该询价单全部待处理项目处理完成，可以提交");
                    }
                }
                catch (Exception ex)
                {

                }
            }
        }
        protected void rpList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {//加载明细
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    Repeater rpSub = (Repeater)e.Item.FindControl("rpSub");
                    HiddenField hdf = (HiddenField)e.Item.FindControl("hdfOid");
                    if (rpSub != null && hdf != null)
                    {
                        DataTable dt = (DataTable)ViewState["dtList"];
                        DataView dv = dt.DefaultView;
                        dv.RowFilter = "OID='" + hdf.Value + "'";//筛出要处理的项
                        dt = dv.ToTable();
                        dt.Columns.Add("eventType");//判断状态
                        dt.Columns.Add("ResPeople");//报价人
                        dt.Columns.Add("orignPrice");//原始报价
                        dt.Columns.Add("orignTime");//原始交期
                        dt.Columns.Add("isFinished");//是否处理过
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["rowstatus"].ToString() == "9")
                            {
                                string reqDetailID = dt.Rows[i]["ReqDetailID"].ToString();
                                string resDetailID = dt.Rows[i]["ResDetailID"].ToString();
                                if (resDetailID == "")
                                {
                                    string _stauts = "";
                                    resDetailID = request.getResDetail(reqDetailID, out _stauts);
                                }
                                string queryNum = dt.Rows[i]["Query_num"].ToString();
                                int _queryNum = int.Parse(queryNum);
                                ArrayList finished = (ArrayList)ViewState["finished"];
                                if (finished.Contains(reqDetailID))
                                {
                                    dt.Rows[i]["isFinished"] = "已处理";//已处理
                                }
                                else
                                {
                                    dt.Rows[i]["isFinished"] = "未处理";//未处理
                                }

                                if (!string.IsNullOrEmpty(resDetailID))
                                {//已有报价
                                    DataTable resDetail = request.ResponseBrif(resDetailID);
                                    if (resDetail != null && resDetail.Rows.Count > 0)
                                    {
                                        dt.Rows[i]["eventType"] = "2";//有报价（可填写，也可以直接放过）
                                        dt.Rows[i]["ResPeople"] = resDetail.Rows[0]["tauName"].ToString();
                                        dt.Rows[i]["orignPrice"] = resDetail.Rows[0]["Single_Price"].ToString();
                                        dt.Rows[i]["orignTime"] = resDetail.Rows[0]["deliver_time"].ToString();
                                    }
                                }
                                else
                                {//没有报价
                                    dt.Rows[i]["eventType"] = "1";
                                }
                            }
                            else
                            {
                                dt.Rows[i]["eventType"] = "0";//有正常的报价
                                dt.Rows[i]["isFinished"] = "无需处理";
                            }
                        }
                        rpSub.DataSource = dt;
                        rpSub.DataBind();
                    }
                }

            }
            catch (Exception ex)
            {
                Tips(ex.Message);
            }
        }
        protected void lbnOverRelax_Click(object sender, EventArgs e)
        {//手动新增报价
            LinkButton lbn = (LinkButton)sender;
            LinkButton lbnSave = (LinkButton)lbn.Parent.FindControl("lbnSave");
            Label lblPrice = (Label)lbn.Parent.FindControl("lblPrice");
            TextBox txtPrice = (TextBox)lbn.Parent.FindControl("txtPrice");
            Label lblTime = (Label)lbn.Parent.FindControl("lblTime");
            TextBox txtTime = (TextBox)lbn.Parent.FindControl("txtTime");
            if (lblPrice != null && txtPrice != null && lblTime != null && txtTime != null)
            {
                lblPrice.Visible = false;
                txtPrice.Visible = true;
                lblTime.Visible = false;
                txtTime.Visible = true;
                txtPrice.Text = lblPrice.Text;
                txtTime.Text = lblTime.Text;
                lbnSave.Visible = true;
                lbn.Visible = false;
            }
        }
        protected void lbnSave_Click(object sender, EventArgs e)
        {//保存报价 
            try
            {
                LinkButton lbn = (LinkButton)sender;
                TextBox txtPrice = (TextBox)lbn.Parent.FindControl("txtPrice");
                TextBox txtTime = (TextBox)lbn.Parent.FindControl("txtTime");

                string finalPrice = txtPrice.Text.Trim();
                string time = txtTime.Text.Trim();
                decimal _finalPrice = 0;
                int _time = 0;
                if (finalPrice == "")
                {
                    Tips("报价不能为空！");
                    return;
                }
                if (!decimal.TryParse(finalPrice, out _finalPrice) || _finalPrice <= 0)
                {
                    Tips("报价应当为大于0的数字");
                    return;
                }
                if (time == "")
                {
                    Tips("请填写交期！");
                    return;
                }
                if (!int.TryParse(time, out _time) || _time <= 0)
                {
                    Tips("交期应当为大于0的数字！");
                    return;
                }
                string reqDetailID = lbn.CommandArgument;
                //新增报价表头
                string ResponseID = "";
                string ResponseDetailID = "";
                if (!request.isResHeadExist(hdfReqID.Value, ref ResponseID))
                {
                    if (request.AddResHeader(hdfReqID.Value, ref ResponseID) <= 0)
                    {
                        throw new Exception("AddResHeader failed");
                    }
                }
                //新增报价表体
                if (request.AddResDetail(reqDetailID, ResponseID, finalPrice, finalPrice, time, ref ResponseDetailID) <= 0)
                {
                    throw new Exception("AddResDetail failed");
                }
                //更新询价单状态
                if (request.UpdateReqDetail(reqDetailID, ResponseDetailID, finalPrice, finalPrice) <= 0)
                {
                    throw new Exception("UpdateReqDetail failed");
                }
                //标注该条记录已处理
                ArrayList finished = (ArrayList)ViewState["finished"];
                if (!finished.Contains(reqDetailID))
                {
                    finished.Add(reqDetailID);
                }
                ViewState["finished"] = finished;
                //允许反复修改
                BindData();
            }
            catch (Exception ex)
            {
                Tips(ex.Message);
            }
        }
        protected void lbnAllow_Click(object sender, EventArgs e)
        {//许可报价
            try
            {
                LinkButton lbn = (LinkButton)sender;
                HiddenField hdfResDetailID = (HiddenField)lbn.Parent.FindControl("hdfReqDetailID");
                string reqDetailID = lbn.CommandArgument;
                DataTable resDetail = request.ResponseBrif(hdfResDetailID.Value);
                if (resDetail != null && resDetail.Rows.Count > 0)
                {
                    string finalPrice = resDetail.Rows[0]["Single_Price"].ToString();
                    if (request.UpdateReqDetail(reqDetailID, hdfResDetailID.Value, finalPrice, finalPrice) <= 0)
                    {
                        throw new Exception("UpdateReqDetail failed");
                    }
                    else
                    {
                        //标注该条记录已处理
                        ArrayList finished = (ArrayList)ViewState["finished"];
                        if (!finished.Contains(reqDetailID))
                        {
                            finished.Add(reqDetailID);
                        }
                        ViewState["finished"] = finished;
                        BindData();
                    }
                }
                //更新询价单状态
            }
            catch (Exception ex)
            {
                Tips(ex.Message);
            }
        }
        protected void lbnSubmit_Click(object sender, EventArgs e)
        {//提交
            try
            {
                //检查当前询价单状态
                ArrayList finished = (ArrayList)ViewState["finished"];
                DataTable dtList = (DataTable)ViewState["dtList"];
                DataView dv = dtList.DefaultView;
                dv.RowFilter = "rowstatus='9'";
                dtList = dv.ToTable();
                if (dtList.Rows.Count != finished.Count)
                {
                    Tips("尚有为处理的项目，无法提交");
                    return;
                }
                //更改表头状态
                if (!request.CheckReq(hdfReqID.Value))
                {
                    Tips("提交失败！");
                }
                else
                {
                    Tips("处理完成");
                    //推送
                    PushResponse(hdfReqID.Value);
                    CloseWindowRefresh();
                }
            }
            catch (Exception ex)
            {
                Tips(ex.Message);
            }
        }
        private void PushResponse(string requestID)
        {//推送报价
            try
            {
                Dictionary<string, object> parm2 = new Dictionary<string, object>();
                parm2.Add("@RequestID", requestID);
                parm2.Add("@Rowstatus", "");
                DataTable dt = request.getDataTable("SP_ChoiceRespone", parm2);
                if (dt != null && dt.Rows.Count > 0)
                {
                    T_Message Entry = new T_Message();
                    Entry.tmType = "2";
                    Entry.tmfrom = "system";
                    #region 多语言
                    string strTip1 = "";
                    string strLan = _MessageDao.GetUserCountryLan(dt.Rows[0]["RequestID"].ToString());

                    strTip1 = _MessageDao.GetTips("8", strLan);

                    #endregion

                    Entry.tmTitle = strTip1;
                    Entry.tmto = dt.Rows[0]["tauloginid"].ToString();

                    Entry.tmMessage = _MessageDao.CreateMessageByRequestId(dt.Rows[0]["RequestID"].ToString(), Entry.tmType);

                    Entry.toType = "1";
                    Entry.toId = dt.Rows[0]["RequestID"].ToString();

                    Dictionary<string, string> Parm = new Dictionary<string, string>();
                    Parm.Add("RequestId", dt.Rows[0]["RequestID"].ToString());

                    CH.SendMessage(Entry, "3", Parm);
                }


            }
            catch (Exception ex)
            {
                Tips(ex.Message);
            }
        }
        /// <summary>
        /// 关闭窗口，刷新父窗口
        /// </summary>
        public void CloseWindowRefresh()
        {
            string strScript = "<script language=javascript>";
            strScript += "if(window.opener){";
            strScript += "window.opener.location.href=window.opener.location.href";
            strScript += "};";
            strScript += "window.close()";
            strScript += "</script>";
            this.ClientScript.RegisterStartupScript(this.GetType(), "closeWin", strScript.ToString());
        }
        private void GetData(string strRequestId, ref DataTable dtHead, ref DataTable dtList)
        {
            string strUrl = ConfigurationManager.AppSettings["UploadFilePath"];
            Dictionary<string, object> parm = new Dictionary<string, object>();
            parm.Add("@LanId", "zh");
            parm.Add("@RequestId", strRequestId);
            parm.Add("@strUrl", strUrl);
            dtHead = request.getDataTable("SP_SelectRequestDetailHead", parm);

            Dictionary<string, object> parm1 = new Dictionary<string, object>();
            parm1.Add("@LanId", "zh");
            parm1.Add("@RequestId", strRequestId);
            parm1.Add("@strUrl", strUrl);
            dtList = request.getDataTable("SP_SelectRequestDetail", parm1);
            dtList.Columns.Add("Oid");

            #region 匹配明细头、内容
            for (int i = 0; i < dtList.Rows.Count; i++)
            {
                for (int j = 0; j < dtHead.Rows.Count; j++)
                {
                    if (
                        dtList.Rows[i]["RequestID"].ToString() == dtHead.Rows[j]["RequestID"].ToString() &&
                        dtList.Rows[i]["title"].ToString() == dtHead.Rows[j]["title"].ToString() &&
                        dtList.Rows[i]["ProductionID"].ToString() == dtHead.Rows[j]["ProductionID"].ToString() &&
                        dtList.Rows[i]["ProductionDesc"].ToString() == dtHead.Rows[j]["ProductionDesc"].ToString() &&
                        dtList.Rows[i]["MID_B"].ToString() == dtHead.Rows[j]["MID_B"].ToString() &&
                        dtList.Rows[i]["MID_BDesc"].ToString() == dtHead.Rows[j]["MID_BDesc"].ToString() &&
                        dtList.Rows[i]["MID_I"].ToString() == dtHead.Rows[j]["MID_I"].ToString() &&
                        dtList.Rows[i]["MID_S"].ToString() == dtHead.Rows[j]["MID_S"].ToString() &&
                        dtList.Rows[i]["MID_IDesc"].ToString() == dtHead.Rows[j]["MID_IDesc"].ToString() &&
                        dtList.Rows[i]["MID_SDesc"].ToString() == dtHead.Rows[j]["MID_SDesc"].ToString() &&
                        dtList.Rows[i]["args02"].ToString() == dtHead.Rows[j]["args02"].ToString() &&
                        dtList.Rows[i]["args02Desc"].ToString() == dtHead.Rows[j]["args02Desc"].ToString() &&
                        dtList.Rows[i]["args09"].ToString() == dtHead.Rows[j]["args09"].ToString() &&
                        dtList.Rows[i]["args09Desc"].ToString() == dtHead.Rows[j]["args09Desc"].ToString() &&
                        dtList.Rows[i]["args04"].ToString() == dtHead.Rows[j]["args04"].ToString() &&
                        dtList.Rows[i]["args04Desc"].ToString() == dtHead.Rows[j]["args04Desc"].ToString() &&
                        dtList.Rows[i]["args05"].ToString() == dtHead.Rows[j]["args05"].ToString() &&
                        dtList.Rows[i]["args06"].ToString() == dtHead.Rows[j]["args06"].ToString() &&
                        dtList.Rows[i]["args07"].ToString() == dtHead.Rows[j]["args07"].ToString() &&
                        dtList.Rows[i]["Level"].ToString() == dtHead.Rows[j]["Level"].ToString() &&
                        dtList.Rows[i]["PressureID"].ToString() == dtHead.Rows[j]["PressureID"].ToString() &&
                        dtList.Rows[i]["PressureIDDesc"].ToString() == dtHead.Rows[j]["PressureIDDesc"].ToString() &&
                        dtList.Rows[i]["ConnID"].ToString() == dtHead.Rows[j]["ConnID"].ToString() &&
                        dtList.Rows[i]["ConnDesc"].ToString() == dtHead.Rows[j]["ConnDesc"].ToString() &&
                        dtList.Rows[i]["args01"].ToString() == dtHead.Rows[j]["args01"].ToString() &&
                        dtList.Rows[i]["args08"].ToString() == dtHead.Rows[j]["args08"].ToString() &&
                        dtList.Rows[i]["args03"].ToString() == dtHead.Rows[j]["args03"].ToString() &&
                        dtList.Rows[i]["imgUrl"].ToString() == dtHead.Rows[j]["imgUrl"].ToString())
                    {
                        dtList.Rows[i]["Oid"] = dtHead.Rows[j]["Oid"].ToString();
                    }
                }

            }
            #endregion
        }
        private void Tips(string s)
        {
            StringBuilder strScript = new StringBuilder();
            strScript.Append(@"<script language=javascript>
                var divTips=new jSharp.popUpDiv('divMsg');
                document.getElementById('msgContent').innerHTML='" + s + @"';
                divTips.Show();
                var t=setTimeout(function(){
                    divTips.Close();
                    clearTimeout(t);
                },1000);
            </script>");
            this.ClientScript.RegisterStartupScript(this.GetType(), "tips", strScript.ToString());
        }//提示
        private void WriteRes(string s)
        {
            Response.Clear();
            Response.Write(s);
            Response.Close();
        }
    }
}